<template>
  <div class="product-editor-container">
    <!-- Header Section -->
    <div class="editor-header">
      <div class="form-fields">
        <el-input v-model="product.productName" placeholder="请输入商品标题" class="title-input" clearable />
        <el-input v-model="product.price" placeholder="请输入价格" class="price-input" type="number" min="0" clearable>
          <template #prefix>¥</template>
        </el-input>
        <el-select v-model="selectedCategory" placeholder="选择分类" class="category-select" clearable filterable>

          <el-option v-for="category in categories" :key="category.categoryId" :label="category.categoryName"
            :value="category.categoryId" />
        </el-select>

      </div>

      <div class="action-buttons">
        <el-button @click="goback()" plain>返回</el-button>
        <el-button type="primary" @click="save(1)" v-if="flag == 'save'" :loading="saving">
          发布
        </el-button>
        <el-button type="primary" @click="save(2)" v-else :loading="saving">
          修改
        </el-button>
      </div>
    </div>
    <div>
      <!-- 添加百度网盘URL输入框 -->
      <el-input v-model="product.netdiskUrl" placeholder="请输入百度网盘链接" class="netdisk-input" clearable />
    </div>
    <!-- Image Upload Section -->
    <div class="image-upload-section">
      <div class="upload-title">商品主图</div>
      <el-upload class="avatar-uploader" action="#" :show-file-list="false" :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload" :http-request="customUpload">
        <img v-if="product.imageUrl" :src="product.imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon">
          <Plus />
        </el-icon>
      </el-upload>
      <div class="upload-tip">建议尺寸：800×800像素，支持JPG/PNG格式</div>
    </div>

    <!-- Editor Section -->
    <div class="editor-wrapper" v-loading="loading">
      <div class="editor-title">商品详情</div>
      <editor-vue v-if="isDataReady" :content="product.description" @changeData="hChangeData" />
    </div>
  </div>
</template>

<script>
import editorVue from "../../component/editorVue.vue";
import productApi from "@/api/product";
import categoryApi from "@/api/category";
import { ElMessage } from "element-plus";

export default {
  components: {
    editorVue,
  },
  data() {
    return {
      loading: false,
      saving: false,
      isDataReady: false,
      selectedCategory: null,
      categories: [], // 需要从API获取分类数据
      product: {
        description: "",
        productName: "",
        price: "",
        imageUrl: "",
        netdiskUrl:"",
      },
      flag: "save"
    };
  },
  created() {
    this.load();
    this.fetchCategories(); // 加载分类数据
  },
  methods: {
    async fetchCategories() {
      try {
        const res = await categoryApi.getAllCategories();
        console.log("===============")
        console.log(res)
        console.log("===============")
        this.categories = res.data;
      } catch (error) {
        console.error("获取分类失败:", error);
        this.$message.error("获取分类失败");
      }
    },

    async customUpload(file) {
      this.loading = true;
      try {
        const formData = new FormData();
        formData.append("file", file.file);

        const res = await productApi.uploadImg(formData);
        this.product.imageUrl = res.data;
        this.$message.success("图片上传成功");
      } catch (error) {
        console.error("上传失败:", error);
        this.$message.error("图片上传失败");
      } finally {
        this.loading = false;
      }
    },

    handleAvatarSuccess(response, file) {
      // 处理上传成功
    },

    beforeAvatarUpload(file) {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isImage) {
        this.$message.error('只能上传JPG/PNG格式图片!');
      }
      if (!isLt5M) {
        this.$message.error('图片大小不能超过5MB!');
      }
      return isImage && isLt5M;
    },

    goback() {
      this.$router.go(-1);
    },

    async load() {
      if (this.$route.query.productId) {
        this.loading = true;
        try {
          const res = await productApi.getById(this.$route.query.productId);
          this.product = {
            ...this.product,
            ...res.data
          };
          this.selectedCategory = res.data.categoryId; // 设置选中的分类
          this.flag = 'edit';
        } catch (error) {
          this.$message.error('数据加载失败');
        } finally {
          this.loading = false;
          this.isDataReady = true;
        }
      } else {
        this.flag = 'save';
        this.isDataReady = true;
      }
    },

    async save(flag) {
      this.saving = true;
      try {
        // 添加分类ID到product对象
        const productData = {
          ...this.product,
          categoryId: this.selectedCategory,
        };
        
        if (flag == "1") {
          await productApi.add(productData);
          this.$message.success("发布成功");
        } else {
          await productApi.update(productData);
          this.$message.success("修改成功");
        }
        this.$router.push("/productManage");
      } catch (error) {
        console.error("保存失败:", error);
        this.$message.error("保存失败");
      } finally {
        this.saving = false;
      }
    },

    hChangeData(editDataHtml) {
      this.product.description = editDataHtml;
    },
  },
};
</script>

<style scoped>
.product-editor-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.form-fields {
  display: flex;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

.title-input {
  width: 300px;
}

.price-input {
  width: 180px;
}

.category-select {
  width: 200px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.image-upload-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.upload-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 15px;
  color: #333;
}

.avatar-uploader {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
  margin-bottom: 10px;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.upload-tip {
  font-size: 12px;
  color: #999;
}

.editor-wrapper {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.editor-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 15px;
  color: #333;
}
.netdisk-input{
  margin-bottom: 20px;
  /* width: 300px; */
}
/* 响应式调整 */
@media (max-width: 768px) {
  .form-fields {
    width: 100%;
  }

  .title-input,
  .price-input,
  .category-select {
    width: 100%;
  }

  .action-buttons {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>